package com.zr.domain.caffeine;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CaffeineCacheConfig {

    // 默认全局配置（会被 application.yml 覆盖）
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .maximumSize(1000)
                .recordStats());
        return cacheManager;
    }

    // 为 userCache 定制独立策略（优先级高于全局配置）
    @Bean
    public Caffeine<Object, Object> userCacheBuilder() {
        return Caffeine.newBuilder()
                .expireAfterAccess(1, TimeUnit.HOURS)  // 访问后1小时过期
                .maximumSize(500)                      // 最大500条目
                .weakValues()                          // 值使用弱引用，避免内存泄漏
                .recordStats();                        // 开启统计
    }
}
